package com.yh.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.yh.common.exception.NoStockException;
import com.yh.common.to.mq.OrderTo;
import com.yh.common.to.mq.StockDetailTo;
import com.yh.common.to.mq.StockLockedTo;
import com.yh.common.utils.R;
import com.yh.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.yh.gulimall.ware.entity.WareOrderTaskEntity;
import com.yh.gulimall.ware.feign.OrderFeignService;
import com.yh.gulimall.ware.feign.ProductFeignService;
import com.yh.gulimall.ware.service.WareOrderTaskDetailService;
import com.yh.gulimall.ware.service.WareOrderTaskService;
import com.yh.gulimall.ware.vo.OrderItemVo;
import com.yh.gulimall.ware.vo.OrderVo;
import com.yh.gulimall.ware.vo.SkuHasStockVo;
import com.yh.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yh.common.utils.PageUtils;

import com.yh.gulimall.ware.dao.WareSkuDao;
import com.yh.gulimall.ware.entity.WareSkuEntity;
import com.yh.gulimall.ware.service.WareSkuService;
import com.yh.common.utils.Query;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Resource
    private ProductFeignService productFeignService;

    @Autowired
    OrderFeignService orderFeignService;

    @Resource
    private WareSkuDao wareSkuDao;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WareOrderTaskService orderTaskService;

    @Autowired
    private WareOrderTaskDetailService orderTaskDetailService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        /**
         *    wareId: 123,//仓库id
         *    skuId: 123//商品id
         */
        String warId = (String) params.get("warId");
        if(!StringUtils.isEmpty(warId)){
            wrapper.eq("ware_id", warId);
        }
        String skuId = (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id", skuId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1.需要判断 是否存在库存记录，无就是新增，否则就是修改操作
        List<WareSkuEntity> wareSkuEntities = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(wareSkuEntities==null||wareSkuEntities.size()==0){
            WareSkuEntity SkuEntity = new WareSkuEntity();
            SkuEntity.setSkuId(skuId);
            SkuEntity.setWareId(wareId);
            SkuEntity.setStock(skuNum);
            SkuEntity.setStockLocked(0);
            //远程查询sku的名字 如果失败无需回滚
            //方法1.自己捕获 方法2：服务降级
            try {
                R info = productFeignService.info(skuId);
                if(info.getCode()==0){
                    Map<String,Object> data = (Map<String,Object>) info.get("skuInfo");
                    SkuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){

            }
            this.baseMapper.insert(SkuEntity);
        }else{
            this.baseMapper.addStock(skuId,wareId,skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            //查询当前sku的库存量 (我们所有仓库的库存求和-所有仓库中锁定的库存)
            Long count=baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count==null?false:count>0);
            return vo;
        }).collect(Collectors.toList());

        return collect;
    }

    /**
     * 为某个订单锁定库存
     * @param wareSkuLockVo
     * @return
     *
     * 库存解锁的的场景
     * 1、下单成功，订单过期没有支付被系统自动取消、或者用户手动取消。-》解锁
     * 2、下单成功，库存锁定成功，但是接下来的业务导致订单回滚。-》之前锁定的库存需要解锁
     *      seata解锁太慢了。所以我们采用自动解锁
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo wareSkuLockVo) {
        /**
         * 锁库存前：
         *  保存库存工作单的详情
         *  用来追溯，回滚的。
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        orderTaskService.save(taskEntity);

        //思路：按照下单的收货地址，找到一个就近的仓库，锁定库存。【不做这么复杂】
        //TODO 1、找到每个商品在那个仓库有库存
        List<OrderItemVo> locks = wareSkuLockVo.getLocks();

        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHashSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        //TODO 2、锁定库存
        for (SkuWareHasStock hasStock : collect) {
            //当前商品锁标志
            Boolean curLock=false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if(wareIds==null||wareIds.size()==0){
                //说明有的商品无库存
                throw new NoStockException(skuId);
            }
            //TODO 2.1、 每一个商品都锁成功了。将当前商品锁定了几件的工作单记录发送给MQ
            //TODO 锁定失败。前面保存的工作单信息就回滚了。发出去的消息，即使要解锁记录，数据库查不到id，就不用解锁
            //锁定失败这样式不合理
            for (Long wareId : wareIds) {
                //返回数据库受影响行数 成功返回1 否则就是0
                Long count=wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
                if(count==1){//代表锁定成功
                    curLock=true;
                    /**
                     * 锁定成功保存锁定成功的详情
                     */
                    WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity(null,skuId,"",hasStock.getNum(),taskEntity.getId(),wareId,1);
                    orderTaskDetailService.save(taskDetailEntity);
                    //TODO 告诉MQ库存锁定成功
                    //封装向MQ发送的TO实体
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity,stockDetailTo);
                    lockedTo.setDetailTo(stockDetailTo);

                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);
                    break;
                }else{
                    //当前的仓库锁失败，继续重试下一个仓库
                }
            }
            if(curLock==false){
                //代表当前商品下所有仓库都没有锁住该库存
                throw new NoStockException(skuId);
            }
        }

        //3、上边未抛出异常，说明全部sku锁定库存成功
        return true;
    }

    /**
     * 1、库存自动解锁。-》针对：下单成功，库存锁定成功。之后业务导致下单回滚，库存自动解锁。
     * 2、订单失败：库存锁定失败导致。
     *
     * 只要解锁库存的消息失败。一定要告诉服务器解锁失败，然后进行重试等。（手动ACK机制）
     *
     * @param to
     */
    @Override
    public void unLockStock(StockLockedTo to) {
        StockDetailTo detail = to.getDetailTo();
        Long detailId = detail.getId();
        /**
         * 解锁：
         * 1、查询数据库关于这个订单的锁定库存信息
         * 有：只能证明的是我们库存锁定成功
         *     - 1、没有这个订单。必须解锁
         *     - 2、有这个订单。要根据其状态判断
         *          - 订单状态：已取消：进行解锁
         *          - 订单状态：未取消：不能解锁
         * 没有：库存锁定失败，库存回滚了。这种情况无需解锁。
         */
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
        if(byId!=null){//如果说详情中有记录
            //解锁
            Long id = to.getId();//库存工作单的id-》找寻订单详情
            WareOrderTaskEntity orderTaskEntity = orderTaskService.getById(id);
            String orderSn = orderTaskEntity.getOrderSn();//订单号
            //TODO 远程查询-订单状态 订单状态【0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单】
            R r = orderFeignService.getOrderStatus(orderSn);
            if(r.getCode()==0){//远程调用成功
                OrderVo data = r.getData(new TypeReference<OrderVo>() {
                });
                if(data == null ||data.getStatus() == 4){
                    //订单不存在 或者 被取消 ->进行解锁
                    if(byId.getLockStatus()==1){//当前库存锁定详情处于 1未解锁状态 2已解锁 3已支付
                        unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                    }
                }
            }else{
                //远程调用查询订单状态失败。直接拒绝MQ消息,并且重新放回队列中，让别人继续消费
                throw new RuntimeException("远程服务失败");
            }
        }else{
            //详情中没有记录，代表锁库存失败。不用解锁
        }
    }

    //防止订单服务卡顿，导致订单状态改不了。库存优先到期。导致业务发生错乱（永远不能解锁库存）
    @Transactional
    @Override
    public void unLockStock(OrderTo orderTo) {
        //订单号（根据订单号，找到工作单id，根据工作单id，查一下最新库存的解锁状态，防止重复解锁库存）
        String orderSn = orderTo.getOrderSn();
        WareOrderTaskEntity task=orderTaskService.getOrderTaskByOrderSn(orderSn);
        //库存工作单的id
        Long id = task.getId();
        //按照工作单id找到所有未解锁的库存商品列表，进行解锁
        List<WareOrderTaskDetailEntity> list = orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id)
                .eq("lock_status", 1));
        //解锁列表
        for (WareOrderTaskDetailEntity entity : list) {
            unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }
    }


    /**
     * 解锁库存
     * @param skuId 商品id
     * @param wareId 仓库id
     * @param num 数量
     */
    private void unLockStock(Long skuId,Long wareId,Integer num,Long taskDetailId){
        //库存解锁
        wareSkuDao.unLockStock(skuId,wareId,num);
        //更新库存工作单的状态
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        entity.setLockStatus(2);//变为已解锁
        orderTaskDetailService.updateById(entity);
    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}